package config

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"log"
	"strconv"
	"time"
)

const CAPTCHA = "captcha:"

type RedisStore struct {
	client *redis.Client
}

var RediStore *RedisStore

var ctx = context.Background()

func InitRedisStore() *RedisStore {
	redisConfig := Config.Section("redis")
	host, err := redisConfig.GetKey("Host")
	if err != nil {
		panic(err.Error())
	}
	passwd, err := redisConfig.GetKey("Password")
	if err != nil {
		panic(err.Error())
	}
	db, err := redisConfig.GetKey("DB")
	if err != nil {
		panic(err.Error())
	}
	dbInt, err := strconv.Atoi(fmt.Sprintf("%s", db))
	if err != nil {
		panic(err.Error())
	}
	client := redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s", host),
		Password: fmt.Sprintf("%s", passwd),
		DB:       dbInt,
	})

	RediStore = &RedisStore{client: client}
	//base64Captcha.StoreSyncMap{}(&RediStore)

	return RediStore
}

// set
func (rs *RedisStore) Set(id string, value string) error {
	key := CAPTCHA + id
	err := rs.client.Set(ctx, key, value, time.Minute*10).Err()
	return err
}

// get
func (rs *RedisStore) Get(id string, clear bool) string {
	key := CAPTCHA + id
	val, err := rs.client.Get(ctx, key).Result()
	if err != nil {
		log.Println(err)
		return ""
	}
	if clear {
		err := rs.client.Del(ctx, key).Err()
		if err != nil {
			log.Println(err)
			return ""
		}
	}
	return val
}

//实现验证captcha的方法
func (rs *RedisStore) Verify(id, answer string, clear bool) bool {
	v := rs.Get(id, clear)
	//fmt.Println("key:"+id+";value:"+v+";answer:"+answer)
	return v == answer
}
